//
//  RHBatteryCellFullChartVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/3/11.
//

#import "RHBatteryCellFullChartVC.h"
#import "RHBatteryLoadChartView.h"
#import "DevChartModel.h"
#import "WSDatePickerView.h"
#import "DeviceChartFieldModel.h"

@interface RHBatteryCellFullChartVC ()
@property (nonatomic ,assign) NSInteger cellIndex;

@property (nonatomic ,copy) NSString *packSN;

@property (nonatomic ,strong) RHDeviceModel *devModel;

@property (nonatomic ,strong) RHBatteryLoadChartView *chartView;

@property (nonatomic ,strong) DevChartModel *chartModel;
@end

@implementation RHBatteryCellFullChartVC
- (instancetype)initWithDeviceModel:(RHDeviceModel*)devModel packSN:(NSString*)sn cellIndex:(NSInteger)index
{
    self = [super init];
    if (self) {
        _devModel = devModel;
        _cellIndex = index;
        _packSN = sn;
    }
    return self;
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    NSString *voltKey = [NSString stringWithFormat:@"Pck_CellV_%ld",self.cellIndex];
    NSString *tempKey = [NSString stringWithFormat:@"Pck_Tmp_%ld",self.cellIndex];
    NSArray *cellDataArr = @[
        @{
            @"nickname": voltKey,
            @"comment": @"电芯电压",
            @"unit": @"mV",
            @"min": @(0),
            @"max": @(100),
            @"type": @"number",
            @"format": @"float",
            @"alias": @"电芯电压"
        },
        @{
            @"nickname": tempKey,
            @"comment": @"电芯温度",
            @"unit": @"℃",
            @"min": @(-20),
            @"max": @(100),
            @"type": @"number",
            @"format": @"float",
            @"alias": @"电芯温度"
        }
    ];
    
    self.chartModel = [[DevChartModel alloc]init];
    self.chartModel.dayParams = [NSArray yy_modelArrayWithClass:[DeviceChartFieldModel class] json:cellDataArr];
    self.chartModel.params = [self.chartModel.dayParams mutableCopy];
    NSDate *date = [NSDate date];
    NSTimeInterval interval = [date timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%ld",(NSInteger)interval];
    [self getDataFromNetwork:self.chartModel];
}


- (void)setupUI{
    kWeakSelf;
    QMUIButton *backBtn = [[QMUIButton alloc]init];
    [backBtn setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    [[backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
           delegate.allowRotate = 0;
        if(@available(iOS 16.0, *)) {
            [weakSelf.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
            NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene *ws = (UIWindowScene *)array[0];
            UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
            geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
            [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
                 //业务代码
            }];
        }else{
            NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
            [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
      
    }];
    _chartView = [[RHBatteryLoadChartView alloc] initWithFrame:CGRectMake(kSafe_top, 0,kUI_WINDOW_H - kSafe_top,kUI_WINDOW_W - kSafe_bottom) type:0];
    _chartView.isLandscape = YES;
    
    [self.bgView addSubview:_chartView];
    
    
    _chartView.subTimeBlock = ^{
        [weakSelf subTimeAction];
    };
    
    _chartView.addTimeBlock = ^{
        [weakSelf addTimeAction];
    };

    _chartView.changeTimeBlock = ^{
        [weakSelf changeDate];
    };
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.left.mas_offset(15);
        make.width.height.offset(40);
    }];
    
    [_chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];

 

}

#pragma mark Action - Method
- (void)addTimeAction{
    if (self.chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (self.chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (self.chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (self.chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    [self getDataFromNetwork:self.chartModel];
}

- (void)subTimeAction{
    if (self.chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (self.chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (self.chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (self.chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];

    [self getDataFromNetwork:self.chartModel];
}


 
//变更日期
- (void)changeDate{
    DevChartModel *chartModel = self.chartModel;
    //NSString *dateFormatStr = @"yyyy-MM-dd HH:mm";
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYearMonthDay;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
       
        [self getDataFromNetwork:chartModel];
       
    }];
    datePickerV.dateLabelColor = UIColor.blueColor;//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
 
- (void)updateParams:(DevChartModel *)chartModel{
    
    if (chartModel.timeType == TimeType_Day) {
        [self getDataFromNetwork:chartModel];
    }
//    else if (chartModel.timeType == TimeType_Month){
//        [self getYearOrMonth:YES model:chartModel];
//    }else if (chartModel.timeType == TimeType_Year){
//        [self getYearOrMonth:NO model:chartModel];
//    }
}


#pragma mark - Network
- (void)getDataFromNetwork:(DevChartModel *)chartModel{
    
    [QMUITips showLoadingInView:self.view];
    NSMutableArray *keys = [NSMutableArray array];
    for (DeviceChartFieldModel *fileld in chartModel.selectArray) {
        [keys addObject:fileld.keyCode];
    }

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:23 minute:59 second:59];
    
    NSString *begin_time = [NSString stringWithFormat:@"%zd",(NSInteger)[begin_date timeIntervalSince1970]*1000];
    NSString *end_time = [NSString stringWithFormat:@"%zd",(NSInteger)[end_date timeIntervalSince1970]*1000];
    
    
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,
                           @"endpointTypeCode":@"Pack",
                           @"keyCodes":keys,
                           @"endpointSn":self.packSN,
                           @"startTimestamp":begin_time,
                           @"endTimestamp":end_time
    };
    
    //
    [BaseModel startWithCompletionAPIKey:D_getEndpointDataByTime argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSArray *dataArr = request.responseObject[@"data"];
            //为了让图表显示,造点假数据
            if(dataArr.count == 0){
                [chartModel creatDefaultChartDataWithChartModel];
            }else{
                chartModel.allDataArray = dataArr;
            }
            
            [self.chartView setChartModel:chartModel];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
    }];

}


@end
